<template>
    <!-- <h1>学生管理</h1> -->
    <div class="student">
  
      
      <!-- 搜索框 -->
      <div class="search">
        <el-input
          v-model="searchInput"
          style="width: 240px"
          placeholder="学号/姓名"
          :prefix-icon="Search"
          @keyup.enter="handleSearch"
        />
      </div>
      <!-- 操作台 -->
      <div class="operate">
        <el-button type="primary" @click="dialogVisible = true">添加</el-button>
        <el-button type="danger" @click="delectInBatches()">批量删除</el-button>
        <el-button type="success" @click="handleExport">导出</el-button>
        
      </div>
  
      <!-- 学生信息表单 -->
      <div class="book-list">
        <el-table 
        :data="books" height="460" 
        stripe  style="width: 100%"
        lazy
        @selection-change="handleSelectionChange"
        >
          <!-- 无数据时显示 -->
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
          <el-table-column type="selection" width="40" />
          <el-table-column prop="stuNo" label="学号" sortable min-width="130" />
          <el-table-column prop="stuName" label="姓名" />
          <el-table-column prop="age" label="年龄" sortable width="80"/>
          <el-table-column prop="phone" label="电话" min-width="120"/>
          <el-table-column prop="email" label="邮箱" min-width="120" show-overflow-tooltip resizable/>
          <el-table-column prop="address" label="地址" min-width="120" show-overflow-tooltip resizable/>
          <el-table-column prop="classNo" label="班级" sortable min-width="100" />
          <el-table-column prop="majorName" label="专业" min-width="100"show-overflow-tooltip resizable/>
          <el-table-column prop="collegeName" label="学院" min-width="140"show-overflow-tooltip resizable/>
          <el-table-column prop="courseName" label="选修课程" min-width="90"show-overflow-tooltip resizable/>
          <el-table-column prop="remark" label="备注" min-width="60"show-overflow-tooltip/>
          
          <el-table-column prop="icon" label="操作" min-width="140">
            <template #default="{row}">
              <el-button 
              type="primary" size="small" 
              @click="handleEdit(row)">
              编辑</el-button>
              <el-button 
              type="danger" size="small"
              @click="handleDelete(row)">
              删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          size='small'
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="getStudentListAction"
          @current-change="getStudentListAction"
        />
      </div>
      <!-- 弹出对话框 -->
      <div class="dialog">
        <el-dialog 
        v-model="dialogVisible" 
        :title="(bookInfo.id!==0 ? '编辑学生信息' : '添加学生')" 
        width="500">
      <el-form :model="bookInfo">
        <div style="display: flex;">
          <div style="width: 50%;">
            <!-- 学号 -->
            <el-form-item label="学号" >
              <el-input v-model="bookInfo.stuNo" autocomplete="off" />
            </el-form-item>
            <!-- 姓名 -->
            <el-form-item label="学生姓名" >
              <el-input v-model="studentInfo.stuName" autocomplete="off" />
            </el-form-item>
          </div>
          <!-- 照片 -->
          <el-form-item label="上传照片" >
            <el-input v-model="studentInfo.photo" autocomplete="off" />
          </el-form-item>
        </div>
        
        <div style="display: flex;">
          <div style="width: 50%;">
            <!-- 性别 -->
            <el-form-item label="性别" >
              <el-radio-group v-model="studentInfo.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <!-- 出生日期 -->
          <el-form-item label="出生日期" >
            <el-date-picker
            v-model="studentInfo.birth"
            type="date"
            placeholder="选择出生日期"
          />
          </el-form-item>
        </div>
        <!-- 班级编号 -->
        <el-form-item label="班级编号" >
          <el-input v-model="studentInfo.classNo" autocomplete="off" />
        </el-form-item>
        <!-- 联系方式 -->
        <el-form-item label="联系方式" >
          <el-input v-model="studentInfo.phone" autocomplete="off" />
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" >
          <el-input v-model="studentInfo.email" autocomplete="off" />
        </el-form-item>
        <!-- 家庭地址 -->
        <el-form-item label="家庭地址" >
          <el-input v-model="studentInfo.address" autocomplete="off" />
        </el-form-item>
        <!-- 备注 -->
        <el-form-item label="备注" >
          <el-input v-model="studentInfo.remark" autocomplete="off" />
        </el-form-item>
  
  
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate">
            {{ studentInfo.id!==0 ? '修改' : '添加' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
      </div>
      
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref } from 'vue';
  import { getStudentList, updateStudent, addStudent, deleteStudent, searchStudent } from '../api/student';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Search } from '@element-plus/icons-vue'
  import { utils, writeFileXLSX } from 'xlsx';
  
    const searchInput = ref('')
  
    const students = ref<IStudent[]>([])
    
    // 控制当前页码
    const currentPage = ref<number>(1)
    // 控制总条数
    const total = ref<number>(400)
    // 控制每页显示条数
    const pageSize = ref<number>(10)
  
    // 添加或修改学生数据
    // 控制对话框显隐
    const dialogVisible = ref<boolean>(false)
    // 控制对话框中的学生信息
    const studentInfo = ref<DBStudent>({
      id: 0,
      stuNo: 'STU00000000',
      stuName: '',
      photo: '',
      birth: new Date().toISOString().split('T')[0],
      gender: '',
      phone: '',
      email: '',
      address: '',
      classNo: '',
      majorName: '',
      collegeName: '',
      selectedCourseNo: '',
      remark: ''
    });
    // 获取学生列表
    const getStudentListAction = async () => {
      if(!searchInput.value){
        const res = await getStudentList(currentPage.value, pageSize.value);
        // console.log("res",res)
        students.value = res.students;
        total.value = res.totalCount;
        // if (res.code === 200) {
        //   students.value = res.data.students;
        //   total.value = res.data.total;
        // }
      }
      else{
        // console.log("searchInput.value",searchInput.value);
        const res = await searchStudent(searchInput.value, currentPage.value, pageSize.value);
        // console.log("res",res)
        students.value = res.students;
        total.value = res.totalCount;
        // if (res.code === 200) {
        //   students.value = res.data.students;
        //   total.value = res.data.total;
        //   console.log(students.value)
        // }
      }
    }
  
    getStudentListAction()
  
  
    // 控制选择的学生
    const selectedStudent = ref<IStudent[]>([])
    // 多选
    const handleSelectionChange = (val: IStudent[]) => {
      selectedStudent.value = val;
    }
  
    // 删除单个学生
    const handleDelete = async (stu: DBStudent) => {
      // 获取当前数据
      studentInfo.value = stu;
      // TODO:删除数据
      ElMessageBox.confirm(
        '确定删除该学生吗？', 
        '提示', 
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      // 确定删除
      .then(async() => {
        // 删除
        await deleteStudent(stu.id);
        await getStudentListAction();
        // 成功提示
        ElMessage({
          type: 'success',
          message: '删除成功!',
        });
      })
      .catch(() => {});
      // deleteStudent(stu.id)
    }
    // 批量删除
    const delectInBatches = async () => {
      // TODO:批量删除
      ElMessageBox.confirm(
        '确定删除选中的学生吗？', 
        '提示', 
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      // 确定删除
      .then(async () => {
        // 删除
        selectedStudent.value.forEach(async item => {
          await deleteStudent(item.id);
          await getStudentListAction();
        })
        // 成功提示
        ElMessage({
          type: 'success',
          message: '删除成功!',
        });
      })
      .catch(() => {});
    }
  
    // 编辑学生
    const handleEdit = (stu: IStudent) => {
      // 获取当前数据
      // studentInfo.value = stu;
      const {address, age, classNo, collegeName, email, id, majorName,
        phone, photo, remark, stuName, stuNo
      } = stu;
      studentInfo.value = {
        address,
        gender:'男',
        birth:new Date().toISOString().split('T')[0],
        classNo,
        collegeName,
        selectedCourseNo:'',
        email,
        id,
        majorName,
        phone,
        photo,
        remark,
        stuName,
        stuNo
      }
      // 显示表单
      dialogVisible.value = true;
      console.log("infor:",studentInfo.value)
    }
  
    // 对话框提交
    const handleUpdate = async () => {
      // 隐藏表单
      dialogVisible.value = false;
      // 如果有id，则是编辑（表单不会修改id字段）
      if (studentInfo.value.id!==0) {
        // 编辑
        console.log("studentInfo:",studentInfo.value)
        const res = await updateStudent(studentInfo.value);
        console.log("res:",res)
        // 重新获取学生列表
        getStudentListAction();
        ElMessage('修改成功');
      } else {
        // 添加
        const res = await addStudent(studentInfo.value);
        console.log(res);
        getStudentListAction();
        ElMessage('添加成功');
      }
      
      // 重置表单
      studentInfo.value = {
      id: 0,
      stuNo: 'STU0000000',
      stuName: '',
      photo: '',
      birth: new Date().toISOString().split('T')[0],
      gender: '',
      phone: '',
      email: '',
      address: '',
      classNo: '',
      majorName: '',
      collegeName: '',
      selectedCourseNo: '',
      remark: ''
  }
    }
  
    // 搜索
    const handleSearch = () => {
      // 重置页码
      currentPage.value = 1;
      // searchStudent(searchInput.value,currentPage.value, pageSize.value);
      getStudentListAction();
    }
    // 导出excel文件
    const handleExport = () => {
      // 将需要导出的数据转换为工作表格数据
      const ws = utils.json_to_sheet(students.value);
      // 创建一个工作簿
      const wb = utils.book_new();
      // 将工作表格数据添加到工作簿中
      utils.book_append_sheet(wb, ws, '学生信息');
      // 导出
      writeFileXLSX(wb, '学生信息'+new Date().toLocaleString()+'.xlsx');
    }
  
  </script>
  
  <style scoped lang="scss">
    .student{
      padding-left: 16px;
      padding-right: 16px;
    }
    .search{
      margin-bottom: 16px;
    }
    .operate{
      display: flex;
    }
  </style>
  